<template>
<div>
    <!-- 头部 -->
    <header>
<van-icon name="arrow-left"  @click="back"/><h1>城市选择</h1>
    </header>
<div class="content">
    <!-- 索引栏 -->
<van-index-bar :index-list="indexList" :sticky-offset-top="60">
     <van-index-anchor index="#">
        当前定位
  <van-cell @click="clickFn" :title="now.label" />
     </van-index-anchor>
       <van-index-anchor index="热">
        热门城市
  <van-cell v-for="(item,index) in hotcityList" @click="clickFn" :title="item.label" :key="index"/>

     </van-index-anchor>
  <van-index-anchor v-for="(itemList,index) in cityList" :key="index" :index="itemList[0].short[0].toUpperCase()">{{itemList[0].short[0].toUpperCase()}}
    <van-cell v-for="item in itemList" :title="item.label" :key="item.value" @click="clickFn "/>
  </van-index-anchor>

</van-index-bar>
</div>

</div>
</template>

<script>
import { getCityList, getHotCityList } from '@/api/city'
import { setToken, getToken } from '@/utils/cityStorage'
export default {
  data () {
    return {
      dataList: [],
      cityList: [],
      hotcityList: [],
      indexList: ['#', '热'],
      now: {
        label: '上海',
        value: 'AREA|dbf46d32-7e76-1196',
        pinyin: 'shanghai',
        short: 'sh'
      }
    }
  },
  methods: {
    back () {
      window.history.back()
    },
    clickFn (e) {
      const cityObj = this.dataList.find(item => item.label === e.target.innerText)
      setToken(JSON.stringify(cityObj))
      this.back()
    }
  },
  async  created () {
    console.log(getToken())
    if (getToken()) {
      console.log(JSON.parse(getToken()))
      this.now = JSON.parse(getToken())
    }
    const res = await getCityList()

    this.dataList = res.data.body.sort((a, b) => a.short.localeCompare(b.short))

    let i = 0
    this.dataList.forEach((item, index) => {
      if (index === 0) {
        this.cityList[i] = []
        this.cityList[i].push(item)
      } else {
        if (item.short[0] === this.dataList[index - 1].short[0]) {
          this.cityList[i].push(item)
        } else {
          i++
          this.cityList[i] = []
          this.cityList[i].push(item)
        }
      }
    })
    this.cityList.forEach(item => {
      this.indexList.push(item[0].short[0].toUpperCase())
    })
    const hotCityRes = await getHotCityList()
    console.log(hotCityRes)
    this.hotcityList = hotCityRes.data.body
  }

}
</script>

<style lang="less" scoped>
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
header{
    position: fixed;
    z-index: 999;
    left: 0;
    top: 0;
    width: 100%;
    height: 45px;
    text-align: center;
    line-height: 45px;
    background-color: #f6f5f6;
    h1{
      font-size: 18px;
      color: #333;
      font-weight: 400;
    }
    .van-icon{
        position: absolute;
        left: 15px;
        bottom: 13px;
        font-size: 20px;
        color: #333;
    }
}
.content{
    padding-top: 50px;
}
</style>
